package com.hzit.order.controller;

import com.alipay.api.AlipayApiException;
import com.hzit.order.dto.ItemDTO;
import com.hzit.order.dto.OrderDTO;
import com.hzit.order.entity.Address;
import com.hzit.order.entity.PayLog;
import com.hzit.order.service.IAddressService;
import com.hzit.order.service.IOrderService;
import com.hzit.order.service.IPayLogService;
import com.hzit.order.vo.OrderVO;
import com.ruoyi.system.api.domain.PayAsyncVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ExecutionException;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author wf
 * @since 2024-04-10
 */
@Controller
@RequestMapping
public class OrderController {

	@Autowired
	private IOrderService orderService;
	@Autowired
	private IAddressService addressService;

	@GetMapping({"/","/getOrderInfo.html"})
	public String getOrderInfo(Model model,String ids){
		//1. 在redis中根据id查询出商品列表并放到model中
		List<ItemDTO> itemDTOList = orderService.findItemListByIds(ids);
		//2. 根据登录用户查询用户的地址列表
		List<Address> addresses = addressService.findAddressListByLogin();
		//3. 将查询出的列表放到model中
		model.addAttribute("itemList",itemDTOList);
		//4. 将用户地址放到model中
		model.addAttribute("addressList",addresses);
		//2.2 生成一个token，（订单的幂等性处理，比较订单中的token与redis中的token是否相等）
		String token = orderService.createToken();
		model.addAttribute("token",token);
		model.addAttribute("ids",ids);
		return "getOrderInfo";
	}

	//2 添加订单
	@PostMapping("/order/add")
	public String add(OrderDTO dto,Model model) throws ExecutionException, InterruptedException {
		//2.1 保存订单
		orderService.saveOrder(dto);
		return "redirect:/order/pay";
	}
	@GetMapping("/order/pay")
	public String createPayPage(Model model){
		//2.2 从redis查询出支付日志并保存model中，跳转到支付页面
		PayLog payLog = orderService.getPayLogFromRedis();
		model.addAttribute("payLog",payLog);
		return "pay";
	}

	// 根据登录名显示用户下的订单及订单项列表
	@GetMapping("/order/list")
	public String orderList(Model model){
		List<OrderVO> orderVOS = orderService.findOrderListByLoginName();
		model.addAttribute("orders",orderVOS);
		return "orderlist";
	}

	// 发送异步通知
	@PostMapping("/order/pay/asyncnotify")
	@ResponseBody
	public String asyncNotify(PayAsyncVo vo, HttpServletRequest request) throws AlipayApiException {
		String result = orderService.asyncNotify(request,vo);
		System.out.println("result = " + result);
		return result;
	}
}
